#!/usr/bin/env python
#
#    Copyright (C) 2008 William Waites
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.


"""
Import CAIDA IPv4 Routed /24 AS-Links Data files.

Depending on the command line arguments, the updates are added to a
mesh from an existing datastore or else a new datastore is created.
It is safe to load and save data to the same file, in this manner a
series of updates are added to an existing file.
"""
__usage__ = "%prog [options] input files"

__epilog__ = """
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"""

from adjacencies.version import version
__version__ = "%%prog %s" % (version,)

if __name__ == '__main__':
	from adjacencies.caida import load_aslinks
	from adjacencies.graph import Mesh

	from optparse import OptionParser
	from sys import exit
	import logging
	import shelve

	op = OptionParser(description=__doc__, usage=__usage__,
			epilog=__epilog__, version=__version__)
	op.add_option("--file", "-f", help="File to load data from")
	op.add_option("--save", "-s", help="File to save data to")
	op.add_option("--logfile", "-l", help="Log to file")
	(opts, args) = op.parse_args()

	logcfg = {
		"level": logging.DEBUG,
		"format": '%(asctime)s %(name)-8s %(levelname)-8s %(message)s',
		"datefmt": '%Y/%m/%d %H:%M'
	}
	if opts.logfile:
		logcfg["filename"] = opts.logfile
		logcfg["filemode"] = "a"

	logging.basicConfig(**logcfg)
	log = logging.getLogger("aslinks")

	radix=None

	if opts.file:
		log.info("loading %s", opts.file)
		try:
			db = shelve.open(opts.file, "c")
			mesh = db["mesh"]
		except:
			log.error("failed to load mesh", exc_info=True)
			exit(1)
		if "radix" in db:
			radix = db["radix"]
		db.close()
		log.info("loaded %s", opts.file)
	else:
		mesh = Mesh()

	log.info("mesh has %s vertices and %s edges" % (mesh.order(), len(mesh.edges())))
	for arg in args:
		log.info("importing aslinks from %s", arg)
		try:
			load_aslinks(arg, mesh)
		except:
			log.error("exception importing aslinks", exc_info=True)
		log.info("mesh has %s vertices and %s edges" % (mesh.order(), len(mesh.edges())))

	if opts.save:
		log.info("saving %s", opts.save)
		try:
			db = shelve.open(opts.save, "c")
			db["mesh"] = mesh
			if radix:
				db["radix"] = radix
			db.close()
			log.info("saved %s", opts.save)
		except:
			log.error("failed to save %s", opts.save, exc_info=True)
			exit(1)
